import 'dart:io';

import 'package:app/core/rtc/base/base_socket.dart';
import 'package:app/core/utils/helpers/log_print.dart';

class RtcSocket extends BaseSocket {
  String _url;
  WebSocket _socket;

  RtcSocket(this._url);

  @override
  connect() async {
    try {
      _socket = await _connectForSelfSigned(_url);
      this?.onOpenCallback();
      _socket.listen((data) {
        this?.onMessageCallback(data);
      }, onDone: () {
        this?.onCloseCallback(_socket.closeCode, _socket.closeReason);
      }, onError: (err) {
        this?.onErrorCallback(_socket.closeCode, _socket.closeReason);
      });
    } catch (e) {
      this?.onErrorCallback(500, e.toString());
      LogPrint.getInstance().printDebug('onErrorCallback $_url ${e.toString()}');

    }
  }

  @override
  close() {
    _socket?.close();
  }

  @override
  send(msg) {
    _socket?.add(msg);
  }

  /// 连接ws
  Future<WebSocket> _connectForSelfSigned(String url) async {
    return await WebSocket.connect(url);
  }
}
